/**
 @Author Zhenglinbin
 @Date 2021/3/9
 **/
import { Props } from "@/components/typing";
import { ref, Ref, onMounted, h, reactive } from 'vue';
import store from "@/store";
import { getDateTime } from '@/utils/date-util'
// import { useMultiTab, MultiTabType } from '@/components/multi-tab/multi-tab-store'
import { useRouter, useRoute } from "vue-router";
import { message, Modal } from "ant-design-vue";
import { baseUrl } from "@/setting";
import { get,post ,getQueryVariable} from "@/request/useRequest";

const DealSign = 'AutoSign';
const DealTime = 'AutoTime';
const countersignDeal = 'countersignDeal';

const isNull = (data: any): boolean => {
    return data && data !== 'null'
}
//审批流程——封装的对象
export const workflow = (variables: Props, options: Props, strong = false) => {
    const spinning = ref(false)
    const title = ref('')
    const delayTime = ref(500)
    // const tabs: MultiTabType = useMultiTab()
    const formKey = ref<string>('')
    const notQualityId = ref(false)
    const assignKey = ref('')
    const assign = ref('')
    const keyConfig = ref<Props>({})
    let query={
        flowCode:'',
        formInfo:{},
        formInstance:{},
        formTask:{},
        state:'',
        stateType:1,
        variables:{}
    }
    let id=getQueryVariable("id")
    let formInfoId=getQueryVariable("formInfoId")


    // const query = useRoute().params
    let state: Ref<number> = ref<number>(0)
    let stateType: Ref<number> = ref<number>(-1)
    let formTask: Props = {}
    let formInfo: Props = {}
    const formInstance = ref<Props>({})
    get('formInstance/getFormData',{id,formInfoId}).then((res:any)=>{
        if(res.status==200){
            query.flowCode=res.data.flowCode,
            query.formInfo={...res.data.formInfo}
            get('formInstance/list',{filter:{codeLike:query.flowCode},stateType:1}).then((res:any)=>{
                if(res.status==200){
                    query.formTask={...res.data[0].myTask},
                    query.formInstance={...res.data[0]},
                    query.state=res.data[0].state
                    if (query.state) {
                        state.value = Number(query.state as string)
                    }
                    if (query.stateType) {
                        stateType.value = Number(query.stateType)
                    }
                    if (isNull(query?.formTask)) {
                        formTask = reactive<Props>(query?.formTask as Props)
                    }
                    if (query?.formInfo) {
                        formInfo = reactive<Props>(query?.formInfo as Props)
                        title.value = formInfo.name
                    }
                    if (query?.formInstance) {
                        formInstance.value = reactive<Props>(query?.formInstance as Props)
                    }
                    if (formTask) {
                        formKey.value = formTask.formKey
                        assignKey.value = formTask.reserved
                        assign.value = formTask.reserved2
                    }
                }
            })
        }

    })
    const router = useRouter();
    const user = store.getters['user/user']
    const execute = async () => {
        const tomeout = formInfo?.processKey === 'kuaijianfenxidan' ? 500 : 10
        onMounted(() => {
            setTimeout(() => {
                render()
                generateSing()
            }, tomeout)
        })
    }
    //流程保存
    const save = () => {
        if (!formInfo || Object.keys(formInfo).length < 1) throw new Error('不正确的流程保存，找不到流程定义！')
        let params: Props = {
            formInfoId: formInfo.id
        };
        if (formInstance.value) {
            params.formInstanceId = formInstance.value.id;
        }
        post('formInstance/save', variables.value, params).then(res => {
            //  
            if (res.success && res.data) {
                formInstance.value = res.data
                message.success('保存成功')
            }
        })
    }
    //提交流程
    const start = () => {
        if (strong) {
            if (!validFormField()) return;
        } else {
            if (!validField()) return;
        }
        if (!formInfo || Object.keys(formInfo).length < 1) throw new Error('不正确的流程提交，找不到流程定义！')
        Modal.confirm({
            title: '流程提交',
            content: '您确定要提交该流程吗?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                numberConversion()
                let params: Props = {
                    formInfoId: formInfo.id
                };
                if (formInstance.value) {
                    params.formInstanceId = formInstance.value.id;
                }
                post('formInstance/start', variables.value, params).then(res => {
                    //  
                    if (res.success) {
                        // setTimeout(() => {
                        //     tabs[0].close(formInfo.action)
                        // }, 30)
                        router.push({ path: 'formInstance', query: { stateType: 3 } })
                    }
                })
            }
        })
    }
    const awaken = () => {
        if (strong) {
            if (!validFormField()) return;
        } else {
            if (!validField()) return;
        }
        if (!formInstance.value?.id) throw new Error('不正确的流程唤醒，找不到流程实例！')
        Modal.confirm({
            title: '流程唤醒',
            content: '流程被唤醒后会越过中间审核节点直接跳转至驳回的节点进行审核，您确定要唤醒已驳回的流程吗?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                numberConversion()
                post('formInstance/awaken', variables.value, { formInstanceId: formInstance.value.id }).then(res => {
                    if (res.success) {
                        // setTimeout(() => {
                        //     tabs[0].close(formInfo.action)
                        // }, 30)
                        router.push({ path: 'formInstance', query: { stateType: 3 } })
                    }
                })
            }
        })
    }
    //流程审批
    const deal = (state: number, callback?: Function) => {
        if (!formInstance.value?.id || (!formInfo || Object.keys(formInfo).length < 1)) throw new Error('不正确的流程操作，找不到流程实例或者流程定义！')
        if (!formInstance.value.myTask || Object.keys(formInstance.value.myTask).length < 1) throw new Error('找不到流程任务！')
        const keys = options[formKey.value]
        if (keys && keys.length > 0) {
            if (assignKey.value && !variables.value.appointUserId) throw new Error('请动态指定办理人')
        }

        if (strong && state === 2) {
            if (!validFormField()) return;
        }
        Modal.confirm({
            title: '流程审批',
            content: '您确定要审核该流程?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                if (callback) callback()
                numberConversion()
                let params = {
                    formTaskId: formInstance.value?.myTask?.id,
                    formInstanceId: formInstance.value.id,
                    state: state
                };
                spinning.value = true
                post('formInstance/deal', variables.value, params).then(res => {
                    if (res.success) {
                        spinning.value = false
                        // setTimeout(() => {
                        //     tabs[0].close(formInfo.action)
                        // })
                        router.push({ path: 'success' })
                    }
                }).finally(() => {
                    spinning.value = false
                })
            }
        })
        
    }
    const numberConversion = () => {
        let fields = document.querySelectorAll("div input[type='number']");
        if (fields && fields.length > 0) {
            fields.forEach((item: Props) => {
                variables.value[item.name] = Number(variables.value[item.name])
            })
        }
    }
    const refreshDeal = () => {
        if (formInstance.value && formInstance.value.id) {
            Modal.confirm({
                title: '刷新办理人',
                content: '您确定刷新办理人吗?',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                    let params = {
                        formInstanceId: formInstance.value.id
                    };
                    post('formInstance/refreshDeal', null, params).then(res => {
                        if (res.success) {
                            // setTimeout(() => {
                            //     tabs[0].close(formInfo.action)
                            // }, 30)
                            message.success("刷新成功！");
                            router.push({ path: 'formInstance', query: { stateType: 1 } })
                        }
                    })
                }
            })
        }
    }
    const fallback = () => {
        if (!formInstance.value.myTask || Object.keys(formInstance.value.myTask).length < 1) throw new Error('找不到流程任务！')
        Modal.confirm({
            title: '流程回退',
            content: '您确定要回退该流程?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                let params = {
                    formInstanceId: formInstance.value.id,
                    taskId: formInstance.value.myTask?.taskId
                };
                post('formInstance/fallback', variables.value, params).then(res => {
                    if (res.success) {
                        // setTimeout(() => {
                        //     tabs[0].close(formInfo.action)
                        // }, 30)
                        router.push({ path: 'formInstance', query: { stateType: 1 } })
                    }
                })
            }
        })
    }
    const diagram = () => {
        if (formInstance.value?.processInstanceId) {
            Modal.info({
                title: '流程图',
                width: '80%',
                content: h('img', {
                    src: `${baseUrl}process/history/getProcessImg?processInstanceId=${formInstance.value.processInstanceId}&num=${Math.random()}`,
                    style: {
                        border: '1px solid #000000',
                        width: '100%',
                        height: '100%'
                    }
                }),
                style: {
                    top: '40px'
                }
            });
        } else {
            modelDiagram(formInfo?.modelerId)
        }
    }

    const validFormField = () => {
        if (!formKey.value && (state.value === 3 || state.value === 6)) formKey.value = 'add';

        const keys = options[formKey.value]
        let result = true;

        if (keys) {
            keys.forEach((key: string) => {
                const fields: any = document.querySelectorAll(`*[required=${key}], input[name=${key}][required],textarea[name=${key}][required]`);
                if (fields && fields.length > 0) {
                    fields.forEach((item: any) => {
                        if (item.nodeName === 'DIV') {
                            if (!item.innerText || item.innerText === '请选择') {
                                item.style.border = "1.5px solid red";
                                item.placeholder = "请填写此字段!";
                                result = false;
                            } else {
                                item.style.border = "";
                                item.placeholder = "";
                            }
                        } else {
                            if (item?.localName === 'td') {
                                const children = item.children[0]
                                if (children?.localName === 'label') {
                                    if (!children.children[0]?.children[0]?.checked) {
                                        item.style.border = "1.5px solid red";
                                        result = false;
                                    } else {
                                        item.style.border = "";
                                        item.placeholder = "";
                                    }
                                } else if (children?.localName === 'div') {
                                    if (!item.innerText || item.innerText === '请双击选择') {
                                        item.style.border = "1.5px solid red";
                                        result = false;
                                    } else {
                                        item.style.border = "";
                                        item.placeholder = "";
                                    }
                                } else if (item.children[0]?.localName === 'span') {
                                    if (!item.children[0].children[0].children[0].value) {
                                        item.style.border = "1.5px solid red";
                                        item.placeholder = "请填写此字段!";
                                        result = false;
                                    } else {
                                        item.style.border = "";
                                        item.placeholder = "";
                                    }
                                } else {
                                    if (!item.value) {
                                        item.style.border = "1.5px solid red";
                                        item.placeholder = "请填写此字段!";
                                        result = false;
                                    } else {
                                        item.style.border = "";
                                        item.placeholder = "";
                                    }
                                }
                            } else {
                                if (!item.value) {
                                    item.style.border = "1.5px solid red";
                                    item.placeholder = "请填写此字段!";
                                    result = false;
                                } else {
                                    item.style.border = "";
                                    item.placeholder = "";
                                }
                            }
                        }
                    })
                }
            })
        }
        return result;
    }

    const validField = () => {
        let fields: any = document.querySelectorAll("div input[required],textarea[required],div[required],td[required]");
        let result = true;
        if (fields && fields.length > 0) {
            fields.forEach((item: Props) => {
                if (item.nodeName === 'DIV') {
                    if (!item.innerText || item.innerText === '请选择') {
                        item.style.border = "1px solid red";
                        item.placeholder = "请填写此字段!";
                        result = false;
                    } else {
                        item.style.border = "";
                        item.placeholder = "";
                    }
                } else {
                    if (item?.localName === 'td') {
                        const children = item.children[0]
                        if (children?.localName === 'label') {
                            if (!children.children[0]?.children[0]?.checked) {
                                item.style.border = "1px solid red";
                                result = false;
                            } else {
                                item.style.border = "";
                                item.placeholder = "";
                            }
                        } else if (children?.localName === 'div') {
                            if (!item.innerText || item.innerText === '请双击选择') {
                                item.style.border = "1px solid red";
                                result = false;
                            } else {
                                item.style.border = "";
                                item.placeholder = "";
                            }
                        } else if (item.children[0].localName === 'span') {
                            if (!item.children[0].children[0].children[0].value) {
                                item.style.border = "1px solid red";
                                item.placeholder = "请填写此字段!";
                                result = false;
                            } else {
                                item.style.border = "";
                                item.placeholder = "";
                            }
                        } else {
                            if (!item.value) {
                                item.style.border = "1px solid red";
                                item.placeholder = "请填写此字段!";
                                result = false;
                            } else {
                                item.style.border = "";
                                item.placeholder = "";
                            }
                        }
                    } else {
                        if (!item.value) {
                            item.style.border = "1px solid red";
                            item.placeholder = "请填写此字段!";
                            result = false;
                        } else {
                            item.style.border = "";
                            item.placeholder = "";
                        }
                    }
                }
            })
        }
        return result;
    }

    const render = () => {

        if ((state.value === 3 || state.value === 6) && stateType.value === 3) formKey.value = 'add';
        Object.keys(options).forEach(item => {
            options[item].forEach((key: string) => {
                const fields: any = document.querySelectorAll(`*[name=${key}]`);
                console.log("fields.....", fields)
                keyConfig.value[key] = true
                if (fields && fields.length > 0) {
                    fields.forEach((field: any) => {
                        if (field.attributes.formHidden && field.attributes.formHidden.value) {
                            field.style.display = 'none'
                        } else {
                            field.readOnly = true;
                        }
                    })
                }
            })
        })

        Object.keys(options).forEach(item => {
            options[item].forEach((key: string) => {
                const fields: any = document.querySelectorAll(`*[name=${key}]`);
                if (item === formKey.value) {
                    keyConfig.value[key] = false
                    if (fields && fields.length > 0) {
                        fields.forEach((field: any) => {
                            if (field.attributes.formHidden && field.attributes.formHidden.value) {
                                field.style.display = 'inline'
                            } else {
                                field.readOnly = false;
                                if (field.name?.indexOf(DealSign) === -1 && field.name?.indexOf(DealTime) === -1 && !field.readOnly) {
                                    field.style = "background: #ffebab"
                                }
                            }
                        })
                    }
                }
            })
        })
        if (!formInstance || formInstance.value?.createUser === user.id) notQualityId.value = true
    }
    const generateSing = async () => {
        let fields: string[] = options[formKey.value as string];
        if (fields && fields.length > 0) {
            fields.forEach(item => {
                if (item.includes(DealSign)) {
                    variables.value[formKey.value + DealSign] = user.name
                    keyConfig.value[formKey.value + DealSign] = true
                }
                if (item.includes(DealTime)) {
                    variables.value[formKey.value + DealTime] = getDateTime()
                    keyConfig.value[formKey.value + DealTime] = true
                }
            })
        }

        //清空会签意见框
        if (countersignDeal === formKey.value) {
            variables.value[countersignDeal] = ''
        }
    }
    return {
        execute,
        save,
        start,
        awaken,
        deal,
        refreshDeal,
        keyConfig,
        state,
        fallback,
        diagram,
        formKey,
        notQualityId,
        assignKey,
        assign,
        validField,
        spinning,
        delayTime,
        formInstance,
        title
    }
}
export const modelDiagram = (modelerId: string) => {
    if (modelerId) {
        Modal.info({
            title: '模型流程图',
            width: '85%',
            content: h('img', {
                src: `${baseUrl}process/history/getModelImage?modelId=${modelerId}`,
                style: {
                    border: '1px solid #000000',
                    width: '100%',
                    height: '100%'
                }
            }),
            style: {
                top: '40px'
            }
        });
    }
}
